<template>
    <a-form-model
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        class="phone-code-wrap"
        style="width: 100%;"
    >
        <div v-if="title" class="title"> {{ title }}</div>
        <a-form-model-item prop="phone">
            <a-input
                v-model.trim="form.phone"
                size="large"
                placeholder="请输入手机号"
                :maxLength="11"
                :disabled="disabled"
                class="phone-input"
            >
                <a-icon slot="prefix" type="phone" />
            </a-input>
        </a-form-model-item>
        <div style="display: flex">
            <a-form-model-item prop="verificationCode">
                <a-input
                    v-model.trim="form.verificationCode"
                    size="large"
                    placeholder="请输入验证码"
                    :maxLength="4"
                >
                </a-input>
            </a-form-model-item>
            <a-form-model-item style="margin-left: 20px;">
                <a-button
                    type="primary"
                    :disabled="!!smsCount"
                    class="captach-type"
                    @click="onImgCaptcha"
                >
                    {{ smsCount ? `${smsCount}s` : "获取验证码" }}
                </a-button>
            </a-form-model-item>
        </div>
        <a-button v-if="!hasConfirmBtn" style="width: 50%; margin: 0 auto;" type="primary" @click="goNext">下一步</a-button>
        <div style="padding-top: 10px" v-if="hasConfirmBtn">
          <a-button @click="cancel">取消</a-button>
          <a-button @click="doConfirm" style="margin-left: 10px;" type="primary">确定</a-button>
        </div>
    </a-form-model>
</template>

<script>
import { mapGetters } from 'vuex';
import cloneDeep from 'lodash.clonedeep'
import Regex from "@/utils/regex";
import { commonValidate } from "@/utils/util";
import { clearCurrentCacheFlag } from "@/utils/count-down";
import {
  sendPersonelSms
} from "@/services/user";
import {
  ACCOUNT_TYPE_MAP,
  CERTIFICATION_TYPE_MAP,
  LOGIN_TYPE_MAP
} from "@/config/const";
import {
  CAPTCHA_GET_URL,
  CAPTCHA_CHECK_URL
} from "@/services/api";
import {
  checkPhoneSmsCode
} from "@/services/user";
import {
  countDownInterval,
  browserTabChangeHandler,
  browserTabChangeListener
} from '@/utils/count-down'
import { personelSmsCache } from './config'

export default {
  name: "personelInfoPage",
  components: {},
  props: {
    title: {
      type: String,
      default: ''
    },
    updatePhoneCode: {
      type: Function,
      default: () => () => {}
    },
    // 更新下一步
    updateStep: {
      type: Function,
      default: () => () => {}
    },
    status: {
      type: String,
      default: 'send' // 发送：send, 修改：modify
    },
    phone: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: true
    },
    // 是否有确认按钮标识
    hasConfirmBtn: {
      type: Boolean,
      default: false
    },
    cancel: {
      type: Function,
      default: () => () => {}
    },
    confirm: {
      type: Function,
      default: () => () => {}
    },
    // 当前操作的类型
    type: {
      type: String,
      default: ''
    },
    syncSafePhone: {
      type: Function,
      default: () => () => {}
    }
  },
  data() {
    return {
      form: {
        accountType: ACCOUNT_TYPE_MAP.phoneCode,
        verificationCode: "",
        phone: this.phone
      },
      rules: {
        phone: [
          {
            required: true,
            trigger: "blur",
            validator: this.onCheckPhone
          }
        ],
        verificationCode: [
          {
            required: true,
            trigger: "blur",
            validator: this.onCheckCode
          }
        ]
      },
      smsCount: 0, // sms短信验证码倒计时
      smsTimer: null // 定时器
    }
  },
  computed: {
    // 验证类型
    cerificationType() {
      let type = undefined
      const { modifyPwd, modifyPhone, modifyUserName, modifyEmail } = CERTIFICATION_TYPE_MAP
      switch (this.type) {
        case 'phone':
          type = modifyPhone
          break;
        case 'account':
          type = modifyUserName
          break;
        case 'email':
          type = modifyEmail
          break;
        case 'password':
          type = modifyPwd
          break;
        default:
      }
      return type
    },
    ...mapGetters("account", ["loginUserInfo"])
  },
  mounted() {
    countDownInterval(this, false, personelSmsCache) // 倒计时处理
    browserTabChangeListener(true, this) // 监听tab
  },
  destroyed() {
    browserTabChangeListener(false, this) // 移除监听tab
  },
  methods: {
    showModal() {
        this.visible = true;
    },
    // 校验手机号
    onCheckPhone(rule, value, callback) {
      if (!value) {
        callback('请输入手机号')
        return;
      }
      if (!Regex.phone.test(value)) {
        callback('请输入正确格式的手机号')
        return;
      }
      callback()
    },
    // 校验验证码
    onCheckCode(rule, value, callback) {
      if (!value) {
        callback('请输入验证码')
        return;
      }
      if (!Regex.verificationCode.test(value)) {
        callback('请输入正确格式的验证码')
        return;
      }
      callback()
    },
    // 滑块验证
    async onImgCaptcha() {
      if (!this.form.phone?.length) {
        this.$message.error("请输入手机号");
        return
      }
      const params = {
        captchaGetUrl: CAPTCHA_GET_URL,
        captchaCheckUrl: CAPTCHA_CHECK_URL
      }
      const verifyRes = await this.$ifCaptcha.verify(params);
      if (verifyRes) {
        this.getCaptcha(verifyRes);
      } else {
        this.$message.warning("发送验证码失败: 安全验证未完成");
      }
    },
    // 获取验证码
    async getCaptcha(verifyRes) {
      const { phone, accountType } = this.form;
      const params = {
        phone,
        accountType,
        ...verifyRes,
        loginType: LOGIN_TYPE_MAP.code,
        loginMethod: this.loginUserInfo.loginMethod,
        cerificationType: this.cerificationType
      };
      const phoneValidateResult = await commonValidate(this.$refs.ruleFormRef, 'phone')
      if (!phoneValidateResult) return
      const { data: { code, message, data } } = await sendPersonelSms(params);
      if (code !== 200) {
        this.$message.warning(message);
        return
      }
      this.form.verificationCode = data?.smsCode || '';
      this.form.verificationCode && this.$refs.ruleFormRef.validateField('verificationCode'); // 获取验证码后，重新校验
      countDownInterval(this, true, personelSmsCache); // 倒计时处理
    },
    // 下一步
    async goNext() {
      const validateResult = await commonValidate(this.$refs.ruleFormRef)
      if (!validateResult) return
      const { verificationCode, phone, accountType } = this.form
      const params = {
        verificationCode,
        phone,
        accountType,
        cerificationType: this.cerificationType
      }
      const nextResult = await checkPhoneSmsCode(params)
      clearCurrentCacheFlag(personelSmsCache) // 调用接口，即清理缓存
      const { code, data, message } = nextResult.data
      if (code !== 200) {
        this.$message.error(message)
        return
      }
      this.updatePhoneCode(data)
      this.updateStep(false) // 下一步
      this.syncSafePhone(phone) // 同步安全手机号
    },
    // 确认修改的回调 这块只有修改手机号的时候才会触发
    async doConfirm() {
      const confirmValidate = await commonValidate(this.$refs.ruleFormRef)
      if (!confirmValidate) return
      const params = cloneDeep(this.form)
      params.cerificationType = this.cerificationType
      delete params.accountType
      this.confirm(params)
    },
    // tab变化监听
    browserTabChangeHandler() {
      browserTabChangeHandler(this, personelSmsCache)
    }
  }
}
</script>

<style lang="less" scoped>
.phone-code-wrap {
  margin: 0 auto;
  .title {
    width: 200px;
    font-size: 48px;
    text-align: center;
    font-weight: 700;
    color: #212121;
    width: 100%;
    line-height: 100px;
    padding-bottom: 30px;
  }
  .phone-input {
    width: 340px;
  }
}
</style>
